package com.motu.vertx.module.utility.webtool;

import com.motu.vertx.module.utility.mysql.MysqlTool;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.sqlclient.Pool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

// 通用表的操作
public class CommonTableManager {
    private static Logger logger = LoggerFactory.getLogger(CommonTableManager.class);
    /**
     * 写入server库的表act_word 返回dbid
     * @param jdbcClient
     * @param useType
     * @param desData
     * @param mailType
     * @return
     */
    public static Future<Long> takeActWordId(Pool jdbcClient, int useType, JsonObject desData, int mailType) {
        Promise<Long> promise = Promise.promise();
        try {
            long curTime = TimeUtils.getCurTime();
            String wordHashcode = Tool.actWordHashcode(useType, desData);

            String keys = "";
            String values = "";
            JsonArray updateParams = new JsonArray()
                    .add(wordHashcode)
                    .add(curTime)
                    .add(useType)
                    .add(mailType);
            for (Iterator<Entry<String, Object>> iter1 = desData.iterator(); iter1.hasNext(); ) {
                Map.Entry<String, Object> entry1 = iter1.next();
                String key = entry1.getKey();
                String val = (String) entry1.getValue();
                keys += key;
                values += "?";
                if (iter1.hasNext()) {
                    keys += ",";
                    values += ",";
                }
                updateParams.add(val);
            }
            String updateSql = "INSERT INTO act_word (hashcode,add_time,use_type,type,"+keys+") VALUES (?,?,?,?,"+values+") ON DUPLICATE KEY UPDATE add_time = ?";
            updateParams.add(curTime);
            MysqlTool.updateToDb(jdbcClient, updateSql, updateParams, updateHandler -> {
                if (updateHandler.succeeded()) {
                    String searchSql = "SELECT id FROM act_word WHERE hashcode = ?;";
                    JsonArray searchParams = new JsonArray();
                    searchParams.add(wordHashcode);
                    MysqlTool.queryJsonArrayFromDb(jdbcClient, searchSql, searchParams, searchHandler->{
                        if(searchHandler.succeeded()){
                            JsonArray list = searchHandler.result();
                            if (list.size() == 1) {
                                JsonObject actWord = list.getJsonObject(0);
                                long actWordId = actWord.getLong("id");
                                promise.complete(actWordId);

                            } else {
                                promise.fail("hashcode 查询失败!!!");
                            }
                        }else{
                            logger.error("takeActWordId search error:"+searchHandler.cause().getMessage());
                            promise.fail(searchHandler.cause());
                        }
                    });
                } else {
                    logger.error("takeActWordId update error:"+updateHandler.cause().getMessage());
                    promise.fail(updateHandler.cause());
                }
            });
        } catch (Exception e) {
            promise.fail(e);
        }
        return promise.future();
    }
}
